<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <title>User Index</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/node_modules/layui/dist/css/layui.css" rel="stylesheet"></head>
<body>
<!--
本「综合演示」包含：自定义头部工具栏、获取表格数据、表格重载、自定义模板、单双行显示、单元格编辑、自定义底部分页栏、表格相关事件与操作、与其他组件的结合等相对常用的功能，以便快速掌握 table 组件的使用。
-->
<div style="padding: 16px;">

    <table class="layui-hide" id="User" lay-filter="User"></table>

</div>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">

        <form class="layui-form layui-row layui-col-space16" onsubmit="return false;">
            <div class="layui-col-md2 "   style="margin-right: 10px">
                <select id="groupSelect" name="group" lay-search="" lay-filter="groupSelect">
                    <option value="">全部</option>

                </select>
            </div>
            <div class="layui-btn-container">
                <button class="layui-btn " lay-event="add">添加</button>
                <!--        <button id="search" class="layui-btn" lay-submit lay-filter="nameSearch">查找</button>-->
                <!--        <button id="delete" class="layui-btn layui-bg-red" lay-event="delete">批量删除</button>-->
            </div>
        </form>

    </div>

</script>


<script type="text/html" id="barDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">重置密码</a>
        <a class="layui-btn layui-btn-xs layui-bg-red" lay-event="delete">删除</a>
    </div>
</script>
<script src="/node_modules/layui/dist/layui.js"></script>
<script th:inline="none">
    layui.use(['jquery', 'table', 'dropdown', 'form'], function () {
        var $ = layui.jquery;
        var table = layui.table;
        var dropdown = layui.dropdown;
        var form = layui.form;
        var layer = layui.layer;

        // ???
        var selectStatus = 0;
        // group select status
        var groupSelect = "";
        // 角色列表缓存
        var groupList = [];

        
        /* **************** */
        /*     工具栏部分     */
        /* **************** */

        table.on('toolbar(User)', function (obj) {
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var data = checkStatus.data; // 获取选中的数据
            // var othis = lay(this);
            switch (obj.event) {
                case 'delete':
                    if (data.length === 0) return layer.msg('请至少选择一行');

                    layer.confirm('是否确认删除选中数据？', {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        var index = layer.load(0, {shade: false});
                        /* TODO: 执行批量删除选中 */
                        data.forEach(function (item) {
                            console.log("id:", item.id);
                            var id = {id: item.id};
                            $.ajax({
                                type: 'POST',
                                url: "/User/delete",
                                data: id,
                                dataType: 'Integer',
                                success: function (res) {
                                    console.log("rss : ", res);
                                }
                            })
                        });

                        setTimeout(function () {
                        }, 1000);

                        layer.close(index);
                        layer.confirm('删除成功', {
                            btn: ['关闭'] // 按钮
                        }, function(index) {
                            // alert("删除成功！");
                            // table.reload('User');
                            // layer.load(0, {shade: false});
                            // setTimeout(function () {
                            //     layer.closeAll(); // 关闭所有弹出层
                            // }, 1000);
                            // layer.close(index); // 关闭当前的确认弹出层
                        });


                    }, function () {

                    });

                    break;
            }
            return false;
        });


        /* **************** */
        /*    渲染 table     */
        /* **************** */
        table.render({
            before: function (obj) {
                if(groupList.length !== 0){

                }else{
                    $.ajax({
                        url: '/user/userRoleList',
                        type: 'POST',
                        success: function (res) {
                            console.log("res", res);
                            if (res.code === 0) {
                                var roles = res.data;
                                console.log("roles", roles);
                                var roleSelect = $('[name="group"]');
                                roleSelect.empty(); // 清空下拉框
                                // 处理角色数据，去掉多余的前缀和括号
                                var processedRoles = roles.map(function (role) {
                                    return {
                                        role: role.role.replace(/^\[ROLE_|\]$/g, '')
                                    };
                                });
                                roleSelect.append('<option value="">全部</option>');
                                processedRoles.forEach(function (roles) {
                                    groupList.push(roles.role);
                                    roleSelect.append('<option value="' + roles.role + '">' + roles.role + '</option>');
                                });
                                console.log("角色列表",groupList)
                                // form.render('groupSelect'); // 重新渲染下拉框
                            } else {
                                layer.msg('获取角色列表失败');
                            }
                        },
                        error: function () {
                            layer.msg('获取角色列表失败');
                        }
                    });
                }

            },
            elem: '#User',
            id: 'User',
            url: '/user/search',
            method: 'post',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            height: 'full-35', // 最大高度减去其他容器已占有的高度差
            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            page: true,
            limit: 20,
            limits: [20, 50, 100, 200],
            // totalRow: true, // 开启合计行
            cols: [[
                {type: 'checkbox', fixed: 'left'},
                {
                    fixed: 'left', width: '50', title: '序号', sort: true, templet: function (d) {
                        return d.LAY_INDEX + 1;
                    }
                },
                {field: 'id', title: 'id', hide: true},
                {field: 'userName', width: '100', title: '用户名'},
                {field: 'role', width: '100', title: '分组', templet:function (d){
                        return d.role.replace(/^\[ROLE_|\]$/g, '');
                }},
                {field: 'groupId', width: '100', title: '组id', hide: true},
                {field: 'right', width: '150', minWidth: '150', title: '操作', toolbar: '#barDemo'},
            ]],
            done: function () {

            },
            error: function (res, msg) {
                console.log(res, msg)
            }
        });

        // 触发表格复选框选择
        table.on('checkbox(User)', function (obj) {

        });
        /* **************** */
        /*      添加按钮      */
        /* **************** */
        // TODO 添加
        table.on('toolbar(User)', function (obj) {
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch (obj.event) {
                case 'add':
                    var data = checkStatus.data;
                    layer.open({
                        type: 1,
                        area: '550px',
                        resize: false,
                        shadeClose: true,
                        title: '添加',
                        content: `
         <div class="layui-form layui-form-pane" lay-filter="filter-test-layer" style="margin: 16px;">
            <div class="layui-form-item">
              <label class="layui-form-label">用户名</label>
              <div class="layui-input-inline">
                <input type="text" name="userName" value="" placeholder="请输入用户名" lay-verify="required" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">密码</label>
              <div class="layui-input-inline">
                <input type="password" name="userPwd" value="" placeholder="请输入密码" lay-verify="required" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">分组</label>
              <div class="layui-input-inline">
                <select name="role" id="role">
                  <option value="">请选择分组</option>
                  <!-- 动态加载权限选项 -->
                </select>
              </div>
            </div>

            <div class="layui-form-item">
              <label class="layui-form-label">或新分组</label>
              <div class="layui-input-inline">
                <input type="text" name="newRole" id="newRoleInput" placeholder="请输入新分组名称" class="layui-input">
              </div>
            </div>

            <div class="layui-form-item">
              <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">确认</button>
            </div>
          </div>
        `,
                        success: function () {
                            // 对弹层中的表单进行初始化渲染

                            form.render();

                            // 表单提交事件
                            form.on('submit(demo-login)', function (data) {
                                var index = layer.load(0, {shade: false});
                                var field = data.field; // 获取表单字段值


                                var roleSelect = document.getElementById('role').value;
                                var newRoleInput = document.getElementById('newRoleInput').value.trim();

                                if (!roleSelect && !newRoleInput) {
                                    layer.close(index);
                                    layer.msg('请选择一个分组或输入一个新分组', {icon: 5});
                                    return ;
                                }


                                var selectedRole = field.role;
                                var newRole = field.newRole.trim();
                                if (newRole) {
                                    // 如果用户输入了新分组，优先使用新分组
                                    selectedRole = newRole;
                                }
                                delete field.newRole;
                                console.log("数据；",JSON.stringify({
                                    ...field,
                                    role: selectedRole // 使用更新后的role
                                }))
                                // layer.close(index);
                                $.ajax({
                                    url: '/user/add',
                                    method: 'POST',
                                    contentType: 'application/json',  // 指定请求的内容类型
                                    data: JSON.stringify({
                                        ...field,
                                        role: selectedRole // 使用更新后的role
                                    }),
                                    success: function (res) {

                                        layer.close(index);
                                        layer.msg(res.msg,{icon: 1})
                                        table.reload('User');
                                        layer.load(0, {shade: false});
                                        setTimeout(function () {
                                            layer.closeAll(); // 关闭所有弹出层
                                        },1000)



                                    },
                                    error: function (res) {

                                        layer.close(index);
                                        layer.msg("发生错误！",{icon: 2})
                                        table.reload('User');
                                        layer.load(0, {shade: false});
                                        setTimeout(function () {
                                            layer.closeAll(); // 关闭所有弹出层
                                        },1000)



                                    }

                                })
                                return false; // 阻止默认 form 跳转
                            });

                        }
                    });

                    function loadRoles() {
                        if(groupList.length !== 0){
                            console.log("groupList",groupList)
                            var roleSelect = $('[name="role"]');
                            groupList.forEach(function (item) {
                                console.log("item = ",item)
                                roleSelect.append('<option value="' + item + '">' + item + '</option>');
                            });
                            form.render('select'); // 重新渲染下拉框
                        }else{
                            $.ajax({
                                url: '/user/userRoleList',
                                type: 'POST',
                                success: function (res) {
                                    console.log("res", res);
                                    if (res.code === 0) {
                                        var roles = res.data;
                                        console.log("roles", roles);
                                        var roleSelect = $('[name="role"]');
                                        // roleSelect.empty(); // 清空下拉框
                                        // 处理角色数据，去掉多余的前缀和括号
                                        var processedRoles = roles.map(function (role) {
                                            return {
                                                role: role.role.replace(/^\[ROLE_|\]$/g, '')
                                            };
                                        });

                                        processedRoles.forEach(function (roles) {
                                            roleSelect.append('<option value="' + roles.role + '">' + roles.role + '</option>');
                                        });
                                        form.render('select'); // 重新渲染下拉框
                                    } else {
                                        layer.msg('获取角色列表失败');
                                    }
                                },
                                error: function () {
                                    layer.msg('获取角色列表失败');
                                }
                            });
                        }
                    }
                    break;

            }

            // 异步加载权限列表


            // 初始化加载权限列表
            loadRoles();
        });


        /* **************** */
        /*      操作按钮      */
        /* **************** */
        table.on('tool(User)', function (obj){
            var data = obj.data;
            console.log("data = ",data)
            switch (obj.event){
                case 'edit':{
                    var index = layer.load();
                    layer.confirm('确认重置该用户: '+data.userName+"密码???", {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        $.ajax({
                            url: '/user/update',
                            method: 'POST',
                            data: JSON.stringify({
                                userName: data.userName,
                            }),
                            contentType: 'application/json',
                            success: function (res) {
                                layer.close(index);
                                if(res.code === 0){
                                    layer.confirm("重置成功！密码为： "+data.userName+"123456", {
                                        btn:['关闭']
                                    },function() {
                                        layer.closeAll(); // 关闭所有弹出层
                                    });
                                }else{
                                    layer.confirm("重置失败！", {
                                       btn:['关闭']
                                    },function() {
                                        layer.closeAll(); // 关闭所有弹出层
                                    });
                                }


                            },
                            error: function (res) {
                                layer.close(index);
                                layer.confirm(res.msg, {
                                    btn:['关闭']
                                },function() {
                                    layer.closeAll(); // 关闭所有弹出层
                                });


                            }

                        })
                    },function (){
                        layer.closeAll();
                    });


                    break;
                }
                case 'delete':{
                    layer.confirm('确认删除该用户: '+data.userName+"  ???", {
                        btn: ['确定', '关闭'] //按钮
                    }, function () {
                        var index = layer.load(0, {shade: false});
                        console.log("data.id = ",data.id)
                        $.ajax({
                            url: '/user/delete',
                            type: 'POST',
                            contentType: 'application/json',
                            data:
                                JSON.stringify({ userId: data.id }), // 将数据格式修改为 JSON 格式


                            success: function (res) {
                                layer.close(index);

                                if (res.code === 0) {
                                    layer.msg("删除成功！", {icon: 1})
                                } else {
                                    layer.msg("删除失败！", {icon: 2})
                                }
                                table.reload('User');
                                layer.load(0, {shade: false});
                                setTimeout(function () {
                                    layer.closeAll(); // 关闭所有弹出层
                                }, 1000);

                            },
                            error: function () {
                                layer.msg("删除失败！", {icon: 2});
                                table.reload('User');
                                layer.load(0, {shade: false});
                                setTimeout(function () {
                                    layer.closeAll(); // 关闭所有弹出层
                                }, 1000);
                            }
                        });
                    })


                    break;
                }

            }

        })

        /**
         * 选择框监听。查询设备数据
         */
        form.on('select(groupSelect)', function(data) {
            console.log('Selected value:', data.value);
            if(groupSelect === data.value){
                console.log("相同！不进行请求")
                return ;
            }
            table.reloadData('User', {
                where: {
                    role: data.value
                },
                method:'POST',
                page: {
                    curr: 1 // 重新从第一页开始
                },
                done: function(res, curr, count){
                    groupSelect = data.value;
                }
            });
            // 在此处添加其他逻辑以处理选项更改
        });
    });
</script>
</body>
</html>
